<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>角色管理</span>
      </div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" clearable size="small"></el-input>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable size="small">
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom: 10px" @click="handleAdd">添加</el-button>
      <el-table :data="pageData.data" style="width: 100%" border>
        <el-table-column prop="roleId" label="角色编号" width="80px"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleKey" label="权限字符"></el-table-column>
        <el-table-column prop="roleSort" label="显示顺序"></el-table-column>
        <el-table-column prop="status" label="状态" width="80px">
          <template slot-scope="scope">
             {{scope.row.status==1?"停用":"正常"}}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作"  width="240px">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
            <el-button type="success" size="mini" @click="handleDataScope(scope.$index, scope.row)">
              数据权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageData.pageNo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.totalCount">
      </el-pagination>

      <el-dialog :title="saveForm.roleId==null?'新增角色':'修改角色'" :visible.sync="dialogFormVisible">
        <el-form :model="saveForm" :rules="rules" ref="saveForm" label-width="90px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="saveForm.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="权限编码" prop="roleKey">
            <el-input v-model="saveForm.roleKey" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色顺序" prop="roleSort">
            <el-input-number v-model="saveForm.roleSort" autocomplete="off" controls-position="right"></el-input-number>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="saveForm.status">
              <el-radio label="0">正常</el-radio>
              <el-radio label="1">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="权限" prop="postSort">
            <el-tree
              ref="menuTree"
              :data="menuOptions"
              :props="defaultProps"
              show-checkbox
              node-key="menuId"
              empty-text="加载中，请稍后"
             />
          </el-form-item>
          <el-form-item label="备注" >
            <el-input type="textarea" v-model="saveForm.remark" autocomplete="off" style="width:520px"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="doSave">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="分配数据权限" :visible.sync="dialogDataScopeVisible">
        <el-form :model="saveForm"  label-width="90px">
          <el-form-item label="权限范围" prop="dataScope">
            <el-select v-model="saveForm.dataScope" @change="handleDataScopeChange">
              <el-option label="全部数据权限" value="1"></el-option>
              <el-option label="自定义数据权限" value="2"></el-option>
              <el-option label="本部门数据权限" value="3"></el-option>
              <el-option label="本部门及以下数据权限" value="4"></el-option>
              <el-option label="仅本人数据权限" value="5"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据权限" v-show="saveForm.dataScope == 2">
            <el-tree
              ref="deptTree"
              :data="deptOptions"
              :props="defaultProps2"
              show-checkbox
              node-key="deptId"
              empty-text="加载中，请稍后"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogDataScopeVisible = false">取 消</el-button>
          <el-button type="primary" @click="doDataScopeSave">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //查询的数据模型
      searchForm: {
        //过滤条件
        roleName: null,
        status: null,
        
        //分页条件
        pageNo: 1,
        pageSize: 5,
      },
      //权限树数据
      menuOptions:[],
      //部门树数据
      deptOptions:[],
      //权限树的配置选项
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      //部门树的配置选项
      defaultProps2: {
        children: 'children',
        label: 'deptName'
      },
      //分页数据模型
      pageData: {
        data: [], // 分页数据
        pageNo: 1, // 当前页
        pageSize: 5, // 一页的大小
        totalCount: 0, // 总数据量
        totalPageCount: 0, // 总页数
      },
      //控制对话框显示还是隐藏
      dialogFormVisible: false,
      dialogDataScopeVisible:false,
      //新增的数据模型
      saveForm: {
        roleId:null,
        roleName:null,
        roleKey:null,
        status:"0",
        roleSort:null,
        remark:null,
        menuIds:[],
        deptIds:[],
        dataScope:null
      },
      //验证数据模型
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称！", trigger: "blur" },
        ],
        roleKey: [
          { required: true, message: "请输入权限字符！", trigger: "blur" },
        ],
        roleSort: [
          { required: true, message: "请输入角色顺序！", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    //查询角色分页信息
    this.doSearch();
    //查询权限树数据
    this.doTreeSelect();
    //查询部门树数据
    this.doDeptTreeSelect();
  },
  methods: {
    //查询用户信息
    doSearch() {
      this.$axios.get("/api/sys/role/list", {params:this.searchForm})
        .then((res) => {
          if (res.data.code == 200) {
            this.pageData.pageNo = res.data.data.current;
            this.pageData.pageSize = res.data.data.size;
            this.pageData.totalCount = res.data.data.total;
            this.pageData.totalPageCount = res.data.data.pages;
            this.pageData.data = res.data.data.records;
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //查询权限树
    doTreeSelect() {
      this.$axios.get("/api/sys/menu/treeselect")
        .then((res) => {
          if (res.data.code == 200) {
            this.menuOptions = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //查询部门树
    doDeptTreeSelect() {
      this.$axios.get("/api/sys/dept/treeselect")
        .then((res) => {
          if (res.data.code == 200) {
            this.deptOptions = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //改变每页显示的条数
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.doSearch();
    },
    //改变当前的页码数
    handleCurrentChange(val) {
      this.searchForm.pageNo = val;
      this.doSearch();
    },
    //清空新增表单数据
    reset () {
      this.saveForm = {
        roleId:null,
        roleName:null,
        roleKey:null,
        status:"0",
        roleSort:null,
        remark:null,
        menuIds:[],
        deptIds:[],
        dataScope:null
      };
      //清空树
      if(this.$refs.menuTree){
        this.$refs.menuTree.setCheckedKeys([])
      }
      if(this.$refs.deptTree){
        this.$refs.deptTree.setCheckedKeys([])
      }
    },
    //添加
    handleAdd() {
      //1.清空模型数据
      this.reset();
      //2.显示对话框
      this.dialogFormVisible = true;
    },
    //保存
    doSave() {
      this.$refs["saveForm"].validate((vali) => {
        if (vali) {
          //选中的节点
          let checkedKeys = this.$refs.menuTree.getCheckedKeys();
          //半选中的节点
          let halfCheckedKeys = this.$refs.menuTree.getHalfCheckedKeys();
          //2个数组合并
          this.saveForm.menuIds=[...checkedKeys,...halfCheckedKeys];
          //发送ajax请求
          this.$axios.post("/api/sys/role/save", this.saveForm)
            .then((res) => {
              if (res.data.code == 200) {
                //1.关闭对话框
                this.dialogFormVisible = false;
                //2.友好提示
                this.$message.success(res.data.msg);
                //3.刷新表格
                this.doSearch();
              } else {
                //1.友好提示
                this.$message.error(res.data.msg);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
      });
    },
    //编辑
    handleEdit(index, row) {
      //1.清空数据
      this.reset();
      //2.查询要修改的数据
      this.$axios.get("/api/sys/role/view/"+row.roleId).then((res)=>{
         if(res.data.code==200){  
            this.saveForm=res.data.data;
            //设置权限树的默认选中 需要遍历 一个个设置 
            this.saveForm.menuIds.forEach((menuId)=>{
              this.$nextTick(()=>{
                this.$refs.menuTree.setChecked(menuId,true,false);
              })
            })
         }else{
            this.$message.error(res.data.msg);
         }
      }).catch((err)=>{
        console.log(err);
      })
      //3.显示对话框
      this.dialogFormVisible=true;
    },
    //删除
    handleDelete(index, row) {
        this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //1.发送ajax请求
          this.$axios.delete("/api/sys/role/del/"+row.roleSort).then((res)=>{
              if (res.data.code == 200) {
                //1.友好提示
                this.$message.success(res.data.msg);
                //2.刷新表格
                this.doSearch();
              } else {
                //1.友好提示
                this.$message.error(res.data.msg);
              }
          }).catch((err)=>{
              console.log(err);
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    /** 选择角色权限范围触发 */
    handleDataScopeChange (value) {
      if (value !== '2') {
        this.$refs.deptTree.setCheckedKeys([])
      }
    },
    /** 分配数据权限操作 */
    handleDataScope (index,row) {
      //1.清空数据
      this.reset();
      //2.查询要修改的数据
      this.$axios.get("/api/sys/role/view/"+row.roleId).then((res)=>{
         if(res.data.code==200){  
            this.saveForm=res.data.data;
            //设置权限树的默认选中 需要遍历 一个个设置 
            if(this.saveForm.deptIds){
              this.saveForm.deptIds.forEach((deptId)=>{
                this.$nextTick(()=>{
                  this.$refs.deptTree.setChecked(deptId,true,false);
                })
              })
            }
         }else{
            this.$message.error(res.data.msg);
         }
      }).catch((err)=>{
        console.log(err);
      })
      //3.显示对话框
      this.dialogDataScopeVisible=true;
    },
    //保存数据分配
    doDataScopeSave() {
      //选中的节点
      let checkedKeys = this.$refs.deptTree.getCheckedKeys();
      //半选中的节点
      let halfCheckedKeys = this.$refs.deptTree.getHalfCheckedKeys();
      //构造请求参数
      let param={
        roleId:this.saveForm.roleId,
        dataScope:this.saveForm.dataScope,
        deptIds:[...checkedKeys,...halfCheckedKeys]
      }
      //发送ajax请求
      this.$axios.put("/api/sys/role/dataScope", param)
        .then((res) => {
          if (res.data.code == 200) {
            //1.关闭对话框
            this.dialogDataScopeVisible = false;
            //2.友好提示
            this.$message.success(res.data.msg);
          } else {
            //1.友好提示
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
}
</script>

<style scoped>
</style>

